import React from 'react';
import { connect } from 'react-redux';
import { deepFullCopy, messages } from "share/common";
import SlideFrame from 'components/slide-frame';
import ResizeTable from 'components/resize-table';
import SearchArea from 'components/search-area';
import NewExpense from 'containers/my-account/new-expense';
import moment from 'moment';
import './bank-bill-list.scss';
import { Button, Icon, Popover, message } from 'antd';
import bankBillListService from './bank-bill-list.service';
import SplitPage from './splitPage';
import TransformPage from './to-borrow-or-expense';
import NewRepayment from './new-repayment';
import AgentModal from '../didi-expense/agent-modal';
import DiDiService from '../didi-expense/didi-expense.service';
class BankBillList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [{
        width: '100',
        title: messages('common.sequence' /* 序号 */),
        key: 'order',
        dataIndex: 'order',
        render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>
      }, {
        width: '12%',
        title: '交易日期',
        key: 'trsDate',
        dataIndex: 'trsDate',
        render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={moment(text).format('YYYY-MM-DD')}>{moment(text).format('YYYY-MM-DD')}</Popover> : <span>-</span>
      }, {
        width: '15%',
        title: messages('mcd.myAccount.publicServiceCardBankBill.acpName' /* 交易摘要 */),
        key: 'acpName',
        dataIndex: 'acpName',
        render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>
      }, {
        width: '10%',
        title: messages('mcd.myAccount.publicServiceCardBankBill.posCurCod' /* 币种 */),
        key: 'oriCurCod',
        dataIndex: 'oriCurCod',
        render: text => text ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={text}>{text}</Popover> : <span>-</span>
      }, {
        width: '14%',
        title: messages('my-account.key121' /* 交易金额 */),
        key: 'oriCurAmt',
        dataIndex: 'oriCurAmt',
        render: text => text || [0, '0'].includes(text) ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={this.addCommas(Number(text || '0').toFixed(2))}><div style={{ textAlign: 'right' }}>{this.addCommas(Number(text || '0').toFixed(2))}</div></Popover> : <div style={{ textAlign: 'right' }}>0.00</div>
      }, {
        width: '13%',
        title: messages('mcd.myAccount.publicServiceCardBankBill.splitedAmt' /* 已拆分金额 */),
        key: 'oriSplitedAmt',
        dataIndex: 'oriSplitedAmt',
        render: (text, record) => {
          const oriSplitedAmt = record.oriSplitedAmt || 0;
          const oriAssociatedAmt = record.oriAssociatedAmt || 0;
          const realSplitedAmt = oriSplitedAmt - oriAssociatedAmt;
          return text || [0, '0'].includes(text) ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={this.addCommas(Number(realSplitedAmt || '0').toFixed(2))}><div style={{ textAlign: 'right' }}>{this.addCommas(Number(realSplitedAmt || '0').toFixed(2))}</div></Popover> : <div style={{ textAlign: 'right' }}>-</div>
        }
      }, {
        width: '13%',
        title: messages('mcd.myAccount.publicServiceCardBankBill.notSplitedAmt2' /* 待拆分金额 */),
        key: 'oriRemainAmt',
        dataIndex: 'oriRemainAmt',
        render: text => text || [0, '0'].includes(text) ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={this.addCommas(Number(text || '0').toFixed(2))}><div style={{ textAlign: 'right' }}>{this.addCommas(Number(text || '0').toFixed(2))}</div></Popover> : <div style={{ textAlign: 'right' }}>0.00</div>
      }, {
        width: '13%',
        title: messages('mcd.myAccount.publicServiceCardBankBill.loanBillAmt' /* 转因私 */),
        key: 'oriLoanBillAmt',
        dataIndex: 'oriLoanBillAmt',
        render: text => text || [0, '0'].includes(text) ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={this.addCommas(Number(text || '0').toFixed(2))}><div style={{ textAlign: 'right' }}>{this.addCommas(Number(text || '0').toFixed(2))}</div></Popover> : <div style={{ textAlign: 'right' }}>0.00</div>
      }, {
        width: '13%',
        title: messages('mcd.myAccount.publicServiceCardBankBill.invoiceAmt' /* 生成费用 */),
        key: 'oriInvoiceAmt',
        dataIndex: 'oriInvoiceAmt',
        render: text => text || [0, '0'].includes(text) ? <Popover className="tableText" overlayStyle={{ maxWidth: 500 }} placement="topLeft" content={this.addCommas(Number(text || '0').toFixed(2))}><div style={{ textAlign: 'right' }}>{this.addCommas(Number(text || '0').toFixed(2))}</div></Popover> : <div style={{ textAlign: 'right' }}>0.00</div>
      }],
      searchForm: [{
        type: 'date',
        id: 'start',
        event: 'start',
        label: messages('mcd.myAccount.publicServiceCardBankBill.start'/* 交易开始日期 */),
        showSearch: true,
        showTime: false
      }, {
        type: 'date',
        id: 'end',
        event: 'end',
        label: messages('mcd.myAccount.publicServiceCardBankBill.end'/* 交易结束日期 */),
        showSearch: true,
        showTime: false
      }],
      selectedNum: 0,
      selectedRowKeys: [], // 被选中的行的所有id
      selectedOriCurAmt: {}, // 被选中的行的总消费额数据
      selectedRows: [], // 被选中的行的所有数据
      data: [],
      loading: true,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        pageSize: 10,
        size: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      searchCondition: {}, // 搜索条件
      showSplitPage: false, // 是否展示拆分抽屉（拆分）
      showTransformPage: false, // 是否展示转因私或生成费用选择拆分数据的抽屉（转因私/生成费用）
      showNewRepayPage: false, // 是否展示新建还款单抽屉（转因私）
      showExpenseTypeChoose: false, // 是否展示费用类型选择抽屉（生成费用）
      showNewExpensePage: false, // 是否展示新建费用抽屉（生成费用）
      info: {}, // 被选中的拆分记录，只有拆分数据，没有公务卡消费记录
      allSelectedRecords: [], // 既有拆分数据也有公务卡消费记录
      total: null, // 转因私或生成费用被选中的总金额
      params: {}, // 转因私的接口传参
      posCurCod: '', // 转换被选中的拆分记录的入账币种
      transformType: null, // 1：生成费用，2：转因私
      resetTransformPage: null, // 重置转因私或生成费用的金额选择页面
      expenseType: {}, // 被选中的费用类型
      agendVisible: false,
      agentUser: undefined,
      dataList: []
    };
  }

  componentDidMount() {
    // this.getList();
    this.getListData()
  }

  getListData = async () => {
    const data = await DiDiService.getProxyPrincipals();
    if (data.status === 200) {
      if (data.data && data.data.length > 0) {
        this.setState({
          agendVisible: true,
          dataList: data.data
        })
      } else {
        this.setState({
          agendVisible: false
        }, () => {
          this.getList();
        })
      }
    }
    console.log('data', data)
  }

  /**
  * 格式化数字
  * @param {Number} nStr 数字
  */
  addCommas = (nStr) => {
    nStr = nStr + '';
    const x = nStr.split('.');
    let x1 = x[0];
    const x2 = x.length > 1 ? '.' + x[1] : '';
    const rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1,$2');
    }
    return x1 + x2;
  }

  /**
   * 获取公务卡消费记录
   */
  getList = async () => {
    const { pagination, searchCondition, agentUser } = this.state;
    const start = searchCondition.start && moment(searchCondition.start).format('YYYY-MM-DD');
    const end = searchCondition.end && moment(searchCondition.end).format('YYYY-MM-DD');
    let condition = { start, end, orderColumn: 'trs_date' };
    if (agentUser && agentUser.userOID) {
      condition.userOID = agentUser.userOID
    }
    const res = await bankBillListService.getList(condition, { ...pagination });
    if (res.status === 200) {
      this.filterData(res.data);
    }
  }

  /**
   * 对接口获取到的数据进行处理
   * @param {Object} data
   */
  filterData = (data) => {
    const { pagination } = this.state;
    const dataSource = data.records.map((item, index) => {
      return {
        order: index + 1,
        ...item
      };
    });
    pagination.total = data.total;
    this.setState({
      data: dataSource,
      pagination,
      loading: false
    });
  }

  /**
   * 点击清空筛选条件触发
   */
  clearHandle = () => {
    this.setState({
      searchCondition: {}
    }, () => {
      this.getList();
    });
  }

  /**
   * 点击搜索按钮触发table的关键字筛选功能
   * @param {Object} values
   */
  handleSearch = (values) => {
    const { pagination } = this.state;
    const searchCondition = { ...values };
    const start = searchCondition.start;
    const end = searchCondition.end;
    if (start && end && start.isAfter(end)) {
      message.error(messages('mcd.myAccount.publicServiceCardBankBill.searchErrmsg'))
      return false;
    }
    pagination.current = 1;
    pagination.page = 0;
    pagination.total = 0;
    this.setState({
      searchCondition,
      pagination,
      selectedRowKeys: [],
      selectedOriCurAmt: {},
      selectedNum: 0
    }, () => {
      this.getList();
    });
  }

  /**
  * 修改每页最大显示数据数量、页码跳转触发
  * @param {Object} pagination
  * @param {*} filters
  * @param {*} sorter
  */
  onChangePage = (pagination, filters, sorter) => {
    this.setState({
      pagination: {
        current: pagination.current,
        page: pagination.current - 1,
        pageSize: pagination.pageSize,
        size: pagination.pageSize
      },
      loading: true
    }, () => {
      this.getList();
    });
  }

  /**
   * 当筛选表单的表单项发生变化时触发
   * @param {String} key 表单项的event配置
   * @param {Moment} value 表单项的值
   * @param {Object} formVal 整体表单的值
   */
  onSearchFormChange = (key, value, formVal) => {
    const start = formVal.start;
    const end = formVal.end;
    if (start && end && start.isAfter(end)) {
      message.error(messages('mcd.myAccount.publicServiceCardBankBill.searchErrmsg'))
    }
  }

  /**
   * 点击拆分按钮触发
   * 1、选中的数据记录里如果存在总消费金额为负数的记录，不允许拆分
   * 2、显示右侧拆分抽屉
   */
  handleOnSplit = async () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length === 0) {
      message.error(messages('mcd.myAccount.publicServiceCardBankBill.unselectedErrmsg'))
      return false;
    }
    const res = await bankBillListService.getRecordsByIds(selectedRowKeys);
    const obj = {};
    res.data.map((record) => {
      obj[record.id] = record.oriCurAmt;
    });
    if (res.status === 200) {
      this.setState({
        selectedRows: res.data,
        selectedOriCurAmt: obj
      }, () => {
        let errFlag = false;
        Object.keys(obj).some((item) => {
          if (obj[item] < 0) {
            errFlag = true;
            return true;
          }
        });
        if (errFlag) {
          message.error(messages('mcd.myAccount.publicServiceCardBankBill.splitErrmsg'));
          return false;
        }
        this.setState({
          showSplitPage: true
        });
      });
    } else {
      this.setState({
        selectedRowKeys: [],
        selectedRows: [],
        selectedNum: 0,
        selectedOriCurAmt: {}
      });
    }
  }

  /**
   * 转费用按钮
   * 1、转费用的所有消费总金额相加，如果为小于等于0，那么在费用选择页面只有一个“公务卡调整”
   * 2、相加如果为正，那么可以选择所有费用类型
   * 3、选中的币种需要相同
   */
  handleOnToExpense = async () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length === 0) {
      message.error(messages('mcd.myAccount.publicServiceCardBankBill.unselectedErrmsg'))
      return false;
    }
    const res = await bankBillListService.getRecordsByIds(selectedRowKeys);
    const obj = {};
    let namelist = [];
    let oriCurCodSameFlag = true
    res.data.map((record) => {
      namelist.push(record.acpName)
      obj[record.id] = record.oriCurAmt;
      if (res.data[0].oriCurCod !== record.oriCurCod) {
        oriCurCodSameFlag = false
      }
    });
    let nameTrue = false;
    let trueList = Array.from(new Set(namelist));
    if (trueList.length === 1) {
      nameTrue = true;
    }
    if (!oriCurCodSameFlag) {
      message.error('请选择相同币种的消费记录')
      return false;
    }
    if (nameTrue) {
      if (res.status === 200) {
        this.setState({
          selectedRows: res.data,
          selectedOriCurAmt: obj
        }, () => {
          this.setState({
            transformType: 1,
            showTransformPage: true
          });
        });
      }
    } else {
      message.error(messages('mcd.myAccount.publicServiceCardBankBill.refuseDifferenceBusiness'));
    }
  }

  /**
   * 点击转因私按钮触发
   * 1、总消费金额相加小于等于0的数据记录不能转因私
   * 2、选中的币种需要相同
   */
  handleOnToBorrow = async () => {
    const { selectedRowKeys, selectedRows } = this.state;
    if (selectedRowKeys.length === 0) {
      message.error(messages('mcd.myAccount.publicServiceCardBankBill.unselectedErrmsg'));
      return false;
    }
    const res = await bankBillListService.getRecordsByIds(selectedRowKeys);
    const obj = {};
    let oriCurCodSameFlag = true
    res.data.map((record) => {
      obj[record.id] = record.oriCurAmt;
      if (res.data[0].oriCurCod !== record.oriCurCod) {
        oriCurCodSameFlag = false
      }
    });
    if (!oriCurCodSameFlag) {
      message.error('请选择相同币种的消费记录');
      return false;
    }
    if (res.status === 200) {
      this.setState({
        selectedRows: res.data,
        selectedOriCurAmt: obj
      }, () => {
        this.setState({
          transformType: 2,
          showTransformPage: true
        });
      });
    }
  }

  /**
   * 收起右侧操作面板
   * @param {String} type 
   */
  handleOnHideSlide = (type) => {
    switch (type) {
      case 'split':
        this.resetListPage();
        this.setState({
          showSplitPage: false
        });
        break;
      case 'transform':
        this.setState({
          showTransformPage: false
        });
        break;
      default:
        break;
    }
  }

  /**
   * 重置表格选中状态
   */
  resetListPage = () => {
    this.setState({
      showSplitPage: false,
      loading: true,
      selectedNum: 0,
      selectedRowKeys: [], // 被选中的行的所有id
      selectedOriCurAmt: {}, // 被选中的行的总消费额数据
      selectedRows: [], // 被选中的行的所有数据
    }, () => {
      this.getList();
    });
  }

  /**
   * 返回右侧拆分抽屉
   */
  renderSplitPage = () => {
    const { selectedRows } = this.state;
    const records = selectedRows.map((row) => {
      row.showDetails = false;
      return row;
    });
    return (
      <SplitPage
        resetListPage={this.resetListPage}
        getList={this.getList}
        hideSlide={this.handleOnHideSlide}
        records={records}
      />
    );
  }

  /**
   * 返回右侧生成费用或者转因私抽屉
   */
  renderTransformPage = () => {
    const { selectedRows } = this.state;
    const records = selectedRows.map((row) => {
      row.showDetails = false;
      return row;
    });
    return (
      <TransformPage
        showTransformPage={this.state.showTransformPage}
        transformType={this.state.transformType}
        selectedRowKeys={this.state.selectedRowKeys}
        hideSlide={this.handleOnHideSlide}
        records={records}
        setInfo={this.setInfo}
      />
    );
  }

  /**
   * 展示新建还款单抽屉
   */
  handleOnShowNewRepayment = () => {
    this.setState({
      showNewRepayPage: true,
      showTransformPage: false
    });
  }

  /**
   * 新建还款单抽屉关闭
   */
  handleOnNewRepaymentClose = () => {
    this.setState({
      showNewRepayPage: false,
      showTransformPage: true
    });
  }

  /**
   * 新建还款单提交成功之后触发
   */
  handleOnNewRepaymentSubmit = () => {
    this.state.resetTransformPage();
    this.setState({
      showNewRepayPage: false,
      loading: true,
      selectedNum: 0,
      selectedRowKeys: [], // 被选中的行的所有id
      selectedOriCurAmt: {}, // 被选中的行的总消费额数据
      selectedRows: [], // 被选中的行的所有数据
    }, () => {
      this.getList();
    });
  }

  /**
   * 新建费用抽屉关闭
   */
  handleOnNewExpenseClose = () => {
    this.state.resetTransformPage()
    this.setState({
      showNewExpensePage: false,
      loading: true,
      selectedNum: 0,
      selectedRowKeys: [], // 被选中的行的所有id
      selectedOriCurAmt: {}, // 被选中的行的总消费额数据
      selectedRows: [], // 被选中的行的所有数据
    }, () => {
      this.getList();
    });
  }

  /**
   * 费用选择抽屉关闭
   */
  handleOnExpenseTypeChooseClose = () => {
    this.setState({
      showExpenseTypeChoose: false,
      expenseType: {},
      showTransformPage: true
    });
  }

  /**
   * 转因私或生成费用的拆分数据选择抽屉给公务卡消费列表页传用户勾选的要转因私的拆分记录
   * @param {Object} info 被选中的拆分数据，没有公务卡消费记录
   * @param {*} total 被选中的拆分数据的总金额
   * @param {*} params 转因私的接口需要的参数
   * @param {*} posCurCod 入账币种
   * @param {*} allSelectedRecords 被选中的拆分数据包括公务卡消费记录
   */
  setInfo = (info, total, params, posCurCod, allSelectedRecords, handleOnReset) => {
    if (this.state.transformType === 2) {
      this.setState({
        info,
        total,
        params,
        posCurCod,
        allSelectedRecords,
        selectedRows: allSelectedRecords,
        showTransformPage: false,
        showNewRepayPage: true,
        resetTransformPage: handleOnReset
      }, () => {
        handleOnReset();
      });
    } else if (this.state.transformType === 1) {
      this.setState({
        info,
        total,
        params,
        posCurCod,
        allSelectedRecords,
        showTransformPage: false,
        selectedRows: allSelectedRecords,
        resetTransformPage: handleOnReset,
        showNewExpensePage: true
      }, () => {
        handleOnReset();
      });
    }

  }

  /**
   * 设置费用类型
   * @param {Object} expenseType 费用类型
   */
  setExpenseType = (expenseType) => {
    this.setState({
      expenseType,
      showExpenseTypeChoose: false,
      showNewExpensePage: true
    });
  }

  changeAgentData = (isAgent, user) => {
    if (isAgent) {
      this.setState({
        agentUser: user,
        agendVisible: false
      }, () => {
        this.getList();
      })
    } else {
      this.setState({ agendVisible: false }, () => {
        this.getList();
      })
    }
  }

  render() {
    const rowSelection = {
      selectedRowKeys: this.state.selectedRowKeys,
      onChange: async (selectedRowKeys) => {
        this.setState({
          selectedRowKeys,
          selectedNum: selectedRowKeys.length
        });
      }
    };
    const { agendVisible, agentUser } = this.state;
    return (
      <div className={'bankBillPage'}>
        <div className={'pageTitle'}>{messages('mcd.myAccount.publicServiceCardBankBill')}</div>
        <SearchArea
          searchForm={this.state.searchForm}
          clearHandle={this.clearHandle}
          submitHandle={this.handleSearch}
          eventHandle={this.onSearchFormChange}
        />
        <div className={'buttonsContainer'}>
          <Button
            onClick={this.handleOnSplit}
            className={'splitBtn'}
            type={'primary'}
          >
            {messages('mcd.myAccount.publicServiceCardBankBill.split')}
          </Button>
          <Button
            onClick={this.handleOnToExpense}
            className={'toExpenseBtn'}
            type={'primary'}
          >
            {messages('mcd.myAccount.publicServiceCardBankBill.toExpense')}
          </Button>
          <Button
            onClick={this.handleOnToBorrow}
            className={'toBorrowBtn'}
            type={'primary'}
          >
            {messages('mcd.myAccount.publicServiceCardBankBill.toBorrow')}
          </Button>
        </div>
        <ResizeTable
          rowKey={'id'}
          dataSource={this.state.data}
          loading={this.state.loading}
          pagination={this.state.pagination}
          onChange={this.onChangePage}
          columns={this.state.columns}
          rowSelection={rowSelection}
          size={'middle'}
          bordered
        />
        {/** 拆分抽屉 */}
        <SlideFrame
          isShowCloseBtn={false}
          slideFrameKey={'splitFrameKey'}
          title={messages('mcd.myAccount.publicServiceCardBankBill.splitInfo')}
          width={'750px'}
          show={this.state.showSplitPage}
          content={this.renderSplitPage}
        />
        {/* 转因私或生成费用选择已拆分数据 */}
        <SlideFrame
          isShowCloseBtn={false}
          slideFrameKey={'toBorrowPageSlideFrameKey'}
          title={this.state.transformType === 1 ? messages('mcd.myAccount.publicServiceCardBankBill.toExpense') : messages('mcd.myAccount.publicServiceCardBankBill.toBorrow')}
          width={'800px'}
          show={this.state.showTransformPage}
          content={this.renderTransformPage}
        />
        <SlideFrame
          isShowCloseBtn={false}
          show={this.state.showNewRepayPage}
          title={messages('loan-billing.key42') /* 新建还款 */}
          key={'repaymentLoan'}
          content={NewRepayment}
          params={{
            info: this.state.info,
            params: this.state.params,
            total: this.state.total,
            repayFrame: this.state.showNewRepayPage,
            posCurCod: this.state.posCurCod,
            allSelectedRecords: this.state.allSelectedRecords,
            loanRefund: false,
            closeFun: this.handleOnNewRepaymentClose,
            submitFun: this.handleOnNewRepaymentSubmit,
            agentName: agentUser && agentUser.fullName,
            agentOid: agentUser && agentUser.userOID,
          }}
        />
        {/** 生成费用，新建费用页面 */}
        <SlideFrame
          isShowCloseBtn={true}
          onClose={this.handleOnNewExpenseClose}
          slideFrameKey={'expenseTypeChooseSlideFrameKey'}
          title={messages('my-account.key67')}
          width={'800px'}
          show={this.state.showNewExpensePage}
          hasFooter={false}
          content={NewExpense}
          params={{
            type: 1,
            readOnly: true,
            info: this.state.info,
            params: this.state.params,
            total: this.state.total,
            repayFrame: this.state.showNewRepayPage,
            posCurCod: this.state.posCurCod,
            allSelectedRecords: this.state.allSelectedRecords,
            expenseType: this.state.expenseType,
            closeFun: this.handleOnNewExpenseClose,
            nowExpense: null,
            expenseSource: 'expenseType',
            slideFrameShowFlag: this.state.showNewExpensePage,
            businessCardEnabled: false,
            officialCard: true,
            user: this.props.user,
            hasInit: false,
            receiptOperateScene: 2,
            isCopy: false,
            agentName: agentUser && agentUser.fullName,
            agentOid: agentUser && agentUser.userOID,
          }}
        />
        <AgentModal
          visible={agendVisible}
          onChange={this.changeAgentData}
          dataList={this.state.dataList}
        />
      </div>
    );
  }
}

BankBillList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.user,
    loginUser: state.login.loginUser
  };
}
export default connect(mapStateToProps)(BankBillList);
